package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.http.HttpUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.log.client.user.operation.AddUserOperationLogRequest;
import com.zmn.log.client.user.operation.UserOperationLogClient;
import com.zmn.log.client.user.operation.enums.UserType;
import com.zmn.log.client.user.operation.item.DeviceLogItem;
import com.zmn.log.client.user.operation.item.EntryLogItem;
import com.zmn.log.client.user.operation.item.EventLogItem;
import com.zmn.log.client.user.operation.item.UserLogItem;
import com.zmn.log.client.user.operation.item.event.LookAddressEventLogItem;
import com.zmn.log.client.user.operation.item.event.LookMobileEventLogItem;
import com.zmn.log.client.user.operation.item.event.LookOrderEventLogItem;
import com.zmn.manager.redis.RedisManager;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.order.OrderBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderPremissionConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.model.dto.order.OrderUserDetailDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailVO;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderPartBService;
import com.zmn.oms.zmn.business.interfaces.statistics.StatOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import eu.bitwalker.useragentutils.UserAgent;
import io.shardingsphere.api.HintManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类描述：工单列表 公用 controller
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@RequestMapping("/work")
@Slf4j
public class WorkListCommonController extends OmsBaseController {

    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    ZsOrderPartBService zsOrderPartBService;
    @Autowired
    ElasticSearchDataSyncService elasticSearchDataSyncService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderBService orderBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Resource
    private UserOperationLogClient logClient;
    @Resource
    private RedisManager redisManager;
    @Resource
    private StatOrderBService statOrderBService;

    /**
     * 列表页跟单备注ajax接口
     * @param id
     * @return
     */
    @GetMapping(value = "/ajax/track/remark")
    @ResponseBody
    public ResultDTO ajaxTrackRemark(@RequestParam Long id) {

        List<Integer> types = Arrays.asList(
                OrderLogConsts.ORDER_LOG_TYPE_REMARK,
                OrderLogConsts.ORDER_LOG_TYPE_PLAT_MASTER_REMARK,
                OrderLogConsts.ORDER_LOG_TYPE_MASTER_REMARK,
                OrderLogConsts.ORDER_LOG_TYPE_ACROSS_DISTRIBUTE_WAIT_TIME_CODE);
        List<OrderLog> orderLogsByTypes = orderLogBService.findOrderLogsByTypes(id, types);
        return ResultDTO.success(orderLogsByTypes);
    }

    /**
     * 列表页跟单备注ajax接口
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/ajax/track/log")
    @ResponseBody
    public ResultDTO ajaxTrackLog(@RequestParam Long id) {
        List<OrderLog> orderLogsByTypes = Lists.newArrayList();
        orderLogsByTypes.addAll(orderLogBService.findNewTrackLogsByWorkId(id));
        return ResultDTO.success(orderLogsByTypes);
    }

    /**
     * 查看手机号
     *
     * @param orderId
     * @param workId
     * @param moduleId
     * @param type 1：联系电话 2：用户电话 3:用户地址
     * @param index 第几个号码
     * @return
     */
    @GetMapping(value = "/detail/show/hideInfo")
    @ResponseBody
    public ResultDTO showDetailHideInfo(@Valid Long orderId, Long workId, Integer moduleId, Integer type, Integer index) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            moduleId = OrderPremissionConsts.getModuleIdByPlat(orderWork.getPlatWork());
        }

        // 联系电话
        if (Objects.equals(1, type)) {
            if (!StaffAdminService.isPermitted(OrderPremissionConsts.getDetailPermitUrl(moduleId, OrderPremissionConsts.ODP_USER_PHONE))) {
                return ResultDTO.fail("没有查看权限");
            }

            if (Objects.isNull(index)) {
                index = 1;
            }

            String telephone = "";
            switch (index){
                case 1:
                    telephone = orderDetail.getTelephone();
                    break;
                case 2:
                    telephone = orderDetail.getTelephone2();
                    break;
                case 3:
                    telephone = orderDetail.getTelephone3();
                    break;
            }


            String[] split = telephone.split("-");
            if (split.length == 2 && StringUtil.isMobile(split[0])) {
                // 是分机电话，只需要显示电话
                telephone = split[0];
            }

            // 日志
            LookMobileEventLogItem eventLogItem = new LookMobileEventLogItem();
            eventLogItem.setOrderId(String.valueOf(orderId));
            eventLogItem.setBizId(String.valueOf(workId));
            eventLogItem.setChannelId(String.valueOf(orderWork.getChannelId()));
            eventLogItem.setMobile(telephone);
            this.addEventLog(eventLogItem);

            return ResultDTO.success(telephone);
        }

        // 用户电话
        if (Objects.equals(2, type)) {
            if (!StaffAdminService.isPermitted(OrderPremissionConsts.getDetailPermitUrl(moduleId, OrderPremissionConsts.ODP_USER_PHONE))) {
                return ResultDTO.fail("没有查看权限");
            }

            OrderUserDetailDTO userInfo = orderBService.getUserInfo(orderDetail.getUserType(), orderWork.getUserId());
            if (Objects.isNull(userInfo)){
                return ResultDTO.success("");
            }

            // 日志
            LookMobileEventLogItem eventLogItem = new LookMobileEventLogItem();
            eventLogItem.setOrderId(String.valueOf(orderId));
            eventLogItem.setBizId(String.valueOf(workId));
            eventLogItem.setChannelId(String.valueOf(orderWork.getChannelId()));
            eventLogItem.setMobile(userInfo.getMobile());
            this.addEventLog(eventLogItem);

            return ResultDTO.success(userInfo.getMobile());
        }

        // 用户地址
        if (Objects.equals(3, type)) {
            if (!StaffAdminService.isPermitted(OrderPremissionConsts.getDetailPermitUrl(moduleId, OrderPremissionConsts.ODP_USER_ADDRESS))) {
                return ResultDTO.fail("没有查看权限");
            }

            String address = String.join(" ",
                    orderDetail.getProvinceName(),
                    orderDetail.getCityName(),
                    orderDetail.getCountyName(),
                    orderDetail.getStreet(),
                    StringUtils.defaultString(orderDetail.getAddress()));

            // 日志
            LookAddressEventLogItem eventLogItem = new LookAddressEventLogItem();
            eventLogItem.setOrderId(String.valueOf(orderId));
            eventLogItem.setBizId(String.valueOf(workId));
            eventLogItem.setChannelId(String.valueOf(orderWork.getChannelId()));
            eventLogItem.setAddress(address);
            this.addEventLog(eventLogItem);

            return ResultDTO.success(address);
        }


        return ResultDTO.success("");
    }

    /**
     * 工单详情
     */
    @RequestMapping(value = "/detail")
    public ModelAndView detail(Long orderId, Long workId, Integer moduleId) {
        ModelAndView mv = new ModelAndView("work/detail");

        ZsOrderWorkDetailVO detailVo = null;
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setMasterRouteOnly();
            try {
                detailVo = zsOrderWorkQueryBService.findOrderWorkDetail(orderId, workId);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                throw e;
            }
        }

        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            moduleId = OrderPremissionConsts.getModuleIdByPlat(detailVo.getPlatWork());
        }

        zsOrderWorkQueryBService.processUserInfoPermiss(detailVo, moduleId);

        // 子公司权限处理
        this.processSubCompanyPermiss(detailVo);

        mv.addObject("detailVo", detailVo);
        // 校验db 和 es 数据一致性
        validateConsistency(workId, detailVo);

        // 获取配件转换
        //Map<Integer, ZsPartUnitConversionVO> partUnitConversion = zsOrderPartBService.getPartUnitConversion();
        //mv.addObject("conversionMap", partUnitConversion);
        mv.addObject("moduleId", moduleId);
        mv.addObject("staff", getCurrentStaff().getStaffId() + "-" + getCurrentStaff().getStaffName());

        // 日志
        LookOrderEventLogItem eventLogItem = new LookOrderEventLogItem();
        eventLogItem.setOrderId(String.valueOf(orderId));
        eventLogItem.setBizId(String.valueOf(workId));
        eventLogItem.setChannelId(String.valueOf(detailVo.getChannelId()));
        this.addEventLog(eventLogItem);

        return mv;
    }

    /**
     * 提留信息权限处理
     * 执行子公司!=行政子公司时不显示提成信息和算账操作的log
     * @param detailVo
     */
    private void processSubCompanyPermiss(ZsOrderWorkDetailVO detailVo){
        // 所属执行公司
        if (Objects.equals(getCurrentStaff().getCompanyId(), detailVo.getCompanyId())) {
            return;
        }
        // 所属组织架构
        if (Objects.equals(getCurrentStaff().getOrgId(), detailVo.getOrgThreeId())) {
            return;
        }
        // 总部
        if (!super.isBranchCompany()) {
            return;
        }

        // 过滤数据提成信息和算账操作的log
        detailVo.setCommission(null);
        List<OrderLog> orderLogList = detailVo.getLogList().stream().filter(item -> !Objects.equals(item.getType(), OrderLogConsts.ORDER_LOG_TYPE_ACCOUNT)).collect(Collectors.toList());
        detailVo.setLogList(orderLogList);

        // 处理工程师电话权限
        if (CollectionUtils.isNotEmpty(detailVo.getMasterVOList())) {
            detailVo.getMasterVOList().forEach(item -> {
                if (StringUtils.isNotBlank(item.getMasterName())) {
                    item.setMasterName(String.format("%s**", item.getMasterName().substring(0, 1)));
                }
                item.setMasterPhone(MobileUtil.formatHideTel(item.getMasterPhone()));
            });
        }

        if (CollectionUtils.isNotEmpty(detailVo.getMainMasterVOList())) {
            detailVo.getMainMasterVOList().forEach(item -> {
                if (StringUtils.isNotBlank(item.getMasterName())) {
                    item.setMasterName(String.format("%s**", item.getMasterName().substring(0, 1)));
                }
                item.setMasterPhone(MobileUtil.formatHideTel(item.getMasterPhone()));
            });
        }

        if (CollectionUtils.isNotEmpty(detailVo.getSlaveMasterVOList())) {
            detailVo.getSlaveMasterVOList().forEach(item -> {
                if (StringUtils.isNotBlank(item.getMasterName())) {
                    item.setMasterName(String.format("%s**", item.getMasterName().substring(0, 1)));
                }
                item.setMasterPhone(MobileUtil.formatHideTel(item.getMasterPhone()));
            });
        }
    }

    /**
     * 校验 db 和 es 数据是否相同
     * @param workId
     * @param detailVo
     */
    private void validateConsistency(Long workId, ZsOrderWorkDetailVO detailVo) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setId(workId);
        query.setIncludes(Arrays.asList("id", "status", "resultStatus"));
        List<EsOrderWork> orderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (!CollectionUtils.isEmpty(orderWorkList)) {
            EsOrderWork esOrderWork = orderWorkList.get(0);
            Integer status = esOrderWork.getStatus();
            Integer resultStatus = esOrderWork.getResultStatus();
            if (!Objects.equals(status, detailVo.getStatus()) || !Objects.equals(resultStatus, detailVo.getResultStatus())) {
                elasticSearchDataSyncService.syncWorkIndex(detailVo.getOrderId());
            }
        }
    }

    /**
     * 工单操作页面-详情
     */
    @RequestMapping(value = "/modify/detail")
    public ModelAndView modifyDetail(Long orderId, Long workId, Integer moduleId) {
        ModelAndView mv = new ModelAndView("work/modify/detail");
        mv.addObject("orderId", orderId);
        mv.addObject("workId", workId);
        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
            Objects.requireNonNull(orderWork, "工单不能存在");
            moduleId = OrderPremissionConsts.getModuleIdByPlat(orderWork.getPlatWork());
        }
        mv.addObject("moduleId", moduleId);
        return mv;
    }

    /**
     * 查询工单操作权限
     *
     * @param orderId 订单Id
     * @param workId  工单Id
     */
    @RequestMapping(value = "/operate/all/permission")
    @ResponseBody
    public ResultDTO<List<OperatePermissionVO>> operateAllPermission(Long orderId, Long workId, Integer moduleId) {
        Objects.requireNonNull(orderId, "订单号不能为空");
        Objects.requireNonNull(workId, "工单号不能为空");

        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
        Objects.requireNonNull(orderWork, "工单不能存在");

        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            moduleId = OrderPremissionConsts.getModuleIdByPlat(orderWork.getPlatWork());
        }

        List<OperatePermissionVO> operatePermissionVOList = orderWorkOperatePermissionBService.getOperatePermissionByModuleId(orderWork, moduleId,
                GlobalConsts.OPERATE_USER_TYPE_STAFF, super.getCurrentStaff().getStaffId().longValue());
        List<OperatePermissionVO> permissionList = processWorkOperatePermit(operatePermissionVOList, moduleId);
        return ResultDTO.success(permissionList);
    }

    /**
     * 工单操作权限面板
     *
     * @param orderId 订单Id
     * @param workId  工单Id
     */
    @RequestMapping(value = "/operate/all/permission/panel")
    public ModelAndView operateAllPermissionPanel(Long orderId, Long workId, Integer moduleId) {
        Objects.requireNonNull(orderId, "订单号不能为空");
        Objects.requireNonNull(workId, "工单号不能为空");

        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
        Objects.requireNonNull(orderWork, "工单不能存在");

        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            moduleId = OrderPremissionConsts.getModuleIdByPlat(orderWork.getPlatWork());
        }

        ModelAndView mv = new ModelAndView("work/modify/common/operatepanel");
        List<OperatePermissionVO> operatePermissionVOList = orderWorkOperatePermissionBService.getOperatePermissionByModuleId(orderWork, moduleId,
                GlobalConsts.OPERATE_USER_TYPE_STAFF, super.getCurrentStaff().getStaffId().longValue());
        List<OperatePermissionVO> permissionList = processWorkOperatePermit(operatePermissionVOList, moduleId);
        mv.addObject("operateList", permissionList);
        return mv;
    }

    /**
     * 查询工单操作权限
     *
     * @param orderId 订单Id
     * @param workId  工单Id
     * @param type    操作类型
     */
    @RequestMapping(value = "/operate/one/permission")
    @ResponseBody
    public ResultDTO<List<OperatePermissionVO>> operateOnePermission(Long orderId, Long workId, Integer type, Integer moduleId) {
        Objects.requireNonNull(orderId, "订单号不能为空");
        Objects.requireNonNull(workId, "工单号不能为空");
        // 未自动流转完不能操作
        if (OrderConsts.AUTO_FLOW_OP_TYPES.contains(type)) {
            if (redisManager.exists(String.format(RedisKeyConsts.AUTO_FLOW_LOCK, workId))) {
                String operateTypeName = OrderConsts.getOperateTypeName(type);
                OperatePermissionVO fail = OperatePermissionVO.fail("系统在自动[" + operateTypeName + "]中，请稍候操作");
                fail.setId(type);
                fail.setName(operateTypeName);
                return ResultDTO.success(Lists.newArrayList(fail));
            }
        }
        if (NumberUtil.isNullOrZero(moduleId)) {
            // 判断用户所属平台
            OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
            Objects.requireNonNull(orderWork, "工单不能存在");
            moduleId = OrderPremissionConsts.getModuleIdByPlat(orderWork.getPlatWork());
        }

        if (Objects.equals(OrderConsts.ORDER_OP_TYPE_SIGN_IN, type)) {
            return getOperatePermissionVOList(orderId, workId, type, moduleId);
        }
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setMasterRouteOnly();
            return getOperatePermissionVOList(orderId, workId, type, moduleId);
        }
    }

    private ResultDTO<List<OperatePermissionVO>> getOperatePermissionVOList(Long orderId, Long workId, Integer type, Integer moduleId) {
        OperatePermissionVO operatePermissionVO = orderWorkOperatePermissionBService.getOperatePermission(orderId, workId, type,
                GlobalConsts.OPERATE_USER_TYPE_STAFF, super.getCurrentStaff().getStaffId().longValue());
        List<OperatePermissionVO> permissionList = processWorkOperatePermit(Lists.newArrayList(operatePermissionVO), moduleId);
        if (permissionList.isEmpty()) {
            return ResultDTO.fail("暂无权限");
        } else {
            return ResultDTO.success(operatePermissionVO);
        }
    }

    /**
     * 检查权限
     *
     * @param permit 权限code
     */
    @RequestMapping(value = "/check/permit")
    @ResponseBody
    public ResultDTO checkPermit(String permit, Integer moduleId) {

        if(NumberUtil.isNullOrZero(moduleId)){
            // 判断用户所属平台
            moduleId = OrderPremissionConsts.getModuleIdByPlat(super.getCurrentStaff().getPlat());
        }

        String url = permit;
        if(NumberUtil.isNumber(permit)){
            url = OrderPremissionConsts.getPermitUrlByCode(moduleId, Integer.parseInt(permit));
        }

        logger.debug("checkPermit={}", url);
        if (StaffAdminService.isPermitted(url)) {
            return ResultDTO.success();
        } else {
            return ResultDTO.fail("无权限");
        }
    }

    /**
     * 处理工单操作数据权限
     *
     * @param operatePermissionVOList
     * @return
     */
    private List<OperatePermissionVO> processWorkOperatePermit(List<OperatePermissionVO> operatePermissionVOList, Integer moduleId) {

        // logger.info("PermitLitDO(operatePermissionVOList)={}", operatePermissionVOList);
        // logger.info("PermitLitDO(roleIds)={}, moduleId={}", super.getLoginStaff().getRoleIds(), moduleId);

        // 系统管理员显示所有操作
//        Subject subject = SecurityUtils.getSubject();
//        if(subject.hasRole(String.valueOf(OrderPremissionConsts.SUPER_ADMIN_ROLE_ID))) {
//            return operatePermissionVOList;
//        }

        if(moduleId == null){
            return operatePermissionVOList;
        }

        List<OperatePermissionVO> permissionList = Lists.newArrayList();

        // 筛选拥有的操作
        operatePermissionVOList.forEach(e -> {
            String url = OrderPremissionConsts.getPermitUrlByCode(moduleId, e.getId());
            if(StringUtils.isNotBlank(url) && StaffAdminService.isPermitted(url)){
                // 特殊优惠-有总公司承担优惠或子公司承担优惠才显示
                if (Objects.equals(e.getId(), OrderConsts.ORDER_OP_TYPE_DISCOUNT_FREE)) {
                    String hqBearPermitUrl = OrderPremissionConsts.getPermitUrlByModuleId(moduleId, OrderPremissionConsts.ODP_HQ_BEAR_DISCOUNT);
                    String subBearPermitUrl = OrderPremissionConsts.getPermitUrlByModuleId(moduleId, OrderPremissionConsts.ODP_SUB_BEAR_DISCOUNT);
                    if (StaffAdminService.isPermitted(hqBearPermitUrl) || StaffAdminService.isPermitted(subBearPermitUrl)) {
                        permissionList.add(e);
                    }
                } else {
                    permissionList.add(e);
                }
            }
        });

        return permissionList;
    }

    /**
     * 埋点日志
     *
     * @param eventLogItem
     */
    private void addEventLog(EventLogItem eventLogItem) {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            String userAgentStr = httpServletRequest.getHeader("User-Agent");
            UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
            final String site = "zmn-oms-admin";

            UserLogItem staffUserLogItem = new UserLogItem();
            staffUserLogItem.setUserType(UserType.STAFFER);
            staffUserLogItem.setUserId(String.valueOf(super.getCurrentStaff().getStaffId()));
            staffUserLogItem.setUserName(super.getCurrentStaff().getStaffName());

            DeviceLogItem deviceLogItem = new DeviceLogItem();
            deviceLogItem.setIp(HttpUtil.getIPAddress(httpServletRequest));
            if (Objects.nonNull(userAgent)) {
                deviceLogItem.setBrowser(userAgent.getBrowser().getName());
                deviceLogItem.setOs(userAgent.getOperatingSystem().getName());
            }

            EntryLogItem entryLogItem = new EntryLogItem();
            entryLogItem.setEntryType(String.valueOf(GateTypeConsts.GATE_TYPE_PLAT));
            entryLogItem.setEntry(String.valueOf(GateTypeConsts.GATE_PLAT_BACKSTAGE));

            eventLogItem.setSite(site);

            AddUserOperationLogRequest request = new AddUserOperationLogRequest<>();
            request.setUser(staffUserLogItem);
            request.setEntry(entryLogItem);
            request.setDevice(deviceLogItem);
            request.setEvent(eventLogItem);
            request.setClientName(site);

            if (eventLogItem instanceof LookMobileEventLogItem) {
                logClient.addLookMobileEventLog(request);
            } else if (eventLogItem instanceof LookAddressEventLogItem) {
                logClient.addLookAddressEventLog(request);
            } else if (eventLogItem instanceof LookOrderEventLogItem) {
                logClient.addLookOrderEventLog(request);
            }
        } catch (Exception e) {
            log.error("addLookOrderEventLog error：", e);
        }
    }
}
